const router = require('koa-router')()
const multer = require('koa-multer')
const fs = require('fs')
const path = require('path')
const util = require('util')
const mongoose = require('mongoose')
const moment = require('moment')
moment.locale('zh-cn')

const Image = mongoose.model('Image')
const Comment = mongoose.model('Comment')
const rename = util.promisify(fs.rename)
const upload = multer({dest: 'public/uploads/'})

router.get('/', async (ctx, next) => {
  const images = await Image.find().sort({createdAt: -1}).limit(9)

  //统计信息
  const images_count = await Image.find().count()
  const comments_count = await Comment.find().count()
  var views_count = 0
  var likes_count = 0
  var turnover = await Image.aggregate(
    [{ 
      $group:{ _id:null,
        views_count :{ $sum : "$views" },
        likes_count:{ $sum : "$likes" }
      }
    }]
  )
  views_count = turnover[0].views_count
  likes_count = turnover[0].likes_count

  const counts = {
    'images_count':images_count,
    'comments_count':comments_count,
    'views_count':views_count,
    'likes_count':likes_count,
  }

  //最受欢迎
  const populars = await Image.find().sort({'likes': -1}).limit(3)

  //最新评论

  await ctx.render('index', {
    images,
    counts,
    populars
  })

})


router.post('/upload', upload.single('imgfile'), async (ctx, next) => {
  const {body, file} = ctx.req
  const newpath = file.path + path.extname(file.originalname)
  await rename(file.path, newpath)
  const imagepath = path.join(...newpath.split(path.sep).slice(1))
  const image = await Image.create({
    originalname: file.originalname,
    imagepath,
    title: body.title,
    description: body.description
  })
  await ctx.redirect(`/image/${image._id}`)
})

//时间
router.get('/image/:id', async ctx => {
  const image = await Image.findById(ctx.params.id)
  const comments = await Comment.find({
      imageid: image._id
  }).sort({createdAt: -1})
  const list = [];
  for(let index in comments){
     comments[index].time = moment(comments[index].createdAt).fromNow()
  }

  const images_count = await Image.find().count()
  const comments_count = await Comment.find().count()
  var views_count = 0
  var likes_count = 0
  var turnover = await Image.aggregate(
    [{ 
      $group:{ _id:null,
        views_count :{ $sum : "$views" },
        likes_count:{ $sum : "$likes" }
      }
    }]
  )
  views_count = turnover[0].views_count
  likes_count = turnover[0].likes_count

  const counts = {
    'images_count':images_count,
    'comments_count':comments_count,
    'views_count':views_count,
    'likes_count':likes_count,
  }

  const populars = await Image.find().sort({'likes': -1}).limit(3)

  //浏览次数
  const newImage = await Image.findByIdAndUpdate(
    ctx.params.id,
    {$inc: {views: 1}},
    {new: true}
  )  

  await ctx.render('image', {
      comments,
      image,
      counts,
      populars,
      createdAt: moment(image.createdAt).fromNow()
  })

})

//点赞次数
router.post('/likeimage', async ctx => {
  const {imageid} = ctx.request.body
  const newImage = await Image.findByIdAndUpdate(
    imageid,
    {$inc: {likes: 1}},
    {new: true}
  )
  ctx.body = newImage
})

//评论
router.post('/addComment',async ctx => {
  const comment = ctx.request.body
  await Comment.create(comment)
  await ctx.redirect('/image/' + comment.imageid)
})

module.exports = router
